package com.financing.task.invest;
import java.util.Date;
import java.util.List;

import org.apache.log4j.Logger;

import com.financing.enums.invest.BidStatus;
import com.financing.model.invest.Bid;
import com.financing.service.invest.BidService;
import com.financing.service.invest.TradeService;
import com.financing.util.DateUtil;
import com.financing.util.Str;
import com.jfinal.aop.Before;
import com.jfinal.kit.Ret;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.SqlPara;
import com.jfinal.plugin.activerecord.tx.Tx;

/**
 * 自动上标任务
 * @author 无处不在的二叔
 */
public class AutoSubmitBid implements Runnable{

	private static BidService bid = new BidService();	
    private static final Logger logger = Logger.getLogger(AutoSubmitBid.class);
    
	@Override 
	@Before(Tx.class)
	public void run() {

		//logger.error("自动排队上标开始！");
		Date now = new Date();
		
		// 自动排队上标
		List<Bid> list = bid.findByStatus(BidStatus.QUEUING);
		for(Bid b : list){
			SqlPara sqlPara = new SqlPara();
			String where = "select * from bid where (status = 'trading' or status = 'waiting') and type =? ";
			sqlPara.addPara(b.getType());
			if(Str.eq("public", b.getType())) {
				where += " and day_limit = ? ";
				sqlPara.addPara(b.getDayLimit());
			}
			sqlPara.setSql(where+" order by create_time desc");
			Bid old = Bid.me.findFirst(sqlPara);
			// Bid old = Bid.me.findFirst("select * from bid where (status = 'trading' or status = 'waiting') and type =? and day_limit = ?", b.getType(), b.getDayLimit());
			if(old==null || (Str.eq(BidStatus.REPAYING, old.getType()) && (Long.valueOf(DateUtil.getTimeStamp())-old.getInvestStartTime().getTime())>600)){
				 Date ten = new Date(now.getTime()+600000); // 10分钟前的时间
				 b.setStartTime(ten).setEndTime(DateUtil.adjust(now, 3)).setStatus(BidStatus.WAITING).update();
				 logger.error("排队上标ID="+b.getId());
			}
		} 

		// logger.error("自动定时上标开始！");
		// 自动定时上标
		 list = bid.findByStatus(BidStatus.TIMING);
		 for(Bid b : list){
			 if(b.getSubmitTime()!=null && b.getSubmitTime().compareTo(now)<=0){
				b.setStatus(BidStatus.TRADING).update();
				logger.error("定时上标ID="+b.getId());
			 }
		 }
			
		// 获取所有已满标记录
		try {
			logger.error("获取所有已满标记录");
			list = bid.findByStatus(BidStatus.FULL);
			 for(Bid b : list){
				logger.error("满标触发ID==="+b.getId());
				 Ret ret = TradeService.full(b);
				 if(ret.isOk()) {
					// 更新交易记录
					Db.update("update trade set status='repaying' where status='trading' and bid_id=?", b.getId());
				 }
			 } 
		}catch(Exception e) {
			e.printStackTrace();
		}
	}
}
